﻿using Coldairarrow.Entity.Backstage.TheRules;
using Coldairarrow.Entity.Goods;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Backstage.TheRules
{
    public class BS_RebateBusiness : BaseBusiness<BS_Rebate>, IBS_RebateBusiness, ITransientDependency
    {
        readonly Operator _operator;
        public BS_RebateBusiness(IDbAccessor db, Operator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<GetRebateDTO>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            Expression<Func<BS_Rebate, BTB_Goods, GetRebateDTO>> select = (a, b) => new GetRebateDTO
            {
                GoodName = b.GoodsName,
                GoodPic = b.GoodsPic,
                GoodPrice = b.GoodsPrices
            };

            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<BTB_Goods>() on a.GoodsId equals b.ID into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            var where = LinqHelper.True<GetRebateDTO>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<GetRebateDTO, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            where = where.And(x => x.IsDefault);

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<BS_Rebate> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task<List<GetGoosDto>> GetGoodsList(GetGoosDto input)
        {
            var yList = GetIQueryable().WhereIf(!input.Id.IsNullOrEmpty(),x => x.IsDefault && !x.Id.Equals(input.Id)).Select(x => x.GoodsId).ToList();
            var goodList = await (Db.GetIQueryable<BTB_Goods>().Where(x => x.IsSale == true).Select(x => new
            {
                x.ID,
                x.GoodsName,
                x.GoodsPrices
            })).ToListAsync();

            List<GetGoosDto> dList = new List<GetGoosDto>();
            GetGoosDto fModel = new GetGoosDto();
            fModel.GoodName = "商品默认";
            fModel.Id = "****";
            dList.Add(fModel);

            foreach (var item in goodList)
            {
                GetGoosDto sModel = new GetGoosDto();
                sModel.GoodName = item.GoodsName +"/"+ item.GoodsPrices.ToString("0.00");
                sModel.Id = item.ID;
                dList.Add(sModel);
            }

            dList = dList.Where(x => !yList.Contains(x.Id)).ToList();

            if (!input.GoodName.IsNullOrEmpty())
            {
                dList = dList.Where(x => x.GoodName.Contains(input.GoodName)).ToList();
            }

            return dList;
        }

        public async Task AddDataAsync(BS_Rebate data)
        {
            int aCount = GetIQueryable().Where(x => x.GoodsId.Equals(data.GoodsId) && x.IsDefault).Count();
            if (aCount > 0)
            {
                throw new BusException("该商品已设置提成比例，无法重复提交！",-2);
            }

            data.IsDefault = true;

            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(BS_Rebate data)
        {
            int aCount = GetIQueryable().Where(x => !x.Id.Equals(data.Id) && x.GoodsId.Equals(data.GoodsId) && x.IsDefault).Count();
            if (aCount > 0)
            {
                throw new BusException("修改商品已设置提成比例，无法重复提交！", -3);
            }

            var model = GetEntity(data.Id);
            if (!model.GoodsId.Equals(data.GoodsId) || !(model.ReturnDiscount == data.ReturnDiscount))
            {
                data.Id = IdHelper.GetId();
                data.CreatorId = _operator.UserId;
                data.CreateTime = DateTime.Now;
                data.Deleted = false;
                data.IsDefault = true;
      
                //更新其他该商品默认为false
                await UpdateAsync(a => a.GoodsId.Equals(data.GoodsId) && a.IsDefault, c => c.IsDefault = false);

                await InsertAsync(data);
            }
            else
            {
                await UpdateAsync(data);
            }
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        #endregion

        #region 私有成员

        #endregion
    }
}